# 引入分页模块
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import render

# 任务列表
from task.models import Task

@login_required
def task_list(request):
    # 从 url 中提取查询参数
    search = request.GET.get('search')

    # 初始化查询集
    task_list = Task.objects.all()

    # 搜索查询集
    if search:
        task_list = task_list.filter(
            Q(title__icontains=search) |
            Q(body__icontains=search)
        )
    else:
        # 将 search 参数重置为空
        search = ''

    # 每页显示 1 篇文章
    paginator = Paginator(task_list, 3)
    # 获取 url 中的页码
    page = request.GET.get('page')
    # 将导航对象相应的页码内容返回给 tasks
    tasks = paginator.get_page(page)
    # 需要传递给模板（templates）的对象
    context = {
        'tasks': tasks,
        'search': search,
    }
    # render函数：载入模板，并返回context对象
    return render(request, 'task/list.html', context)